package com.qfedu.edu.config;

import com.qfedu.edu.filter.LoginFilter;
import com.qfedu.edu.filter.MyAuthenticationFilter;
import org.framework.edu.service.JwtService;
import org.framework.edu.service.TokenService;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.authentication.logout.LogoutHandler;

import javax.annotation.Resource;

@SpringBootConfiguration
@EnableGlobalMethodSecurity(prePostEnabled = true,securedEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Resource
    private UserDetailsService userDetailsService;
    @Resource
    private PasswordEncoder passwordEncoder;
    @Resource
    private AuthenticationEntryPoint authenticationEntryPoint;
    @Resource
    private LogoutHandler logoutHandler;
    @Resource
    private TokenService tokenService;
    @Resource
    private JwtService jwtService;


    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.exceptionHandling()
                .authenticationEntryPoint(authenticationEntryPoint)  //这个是设置没有权限访问的时候 要执行的方法
                .and().csrf().disable()  //关闭防止跨站点伪造
                .authorizeRequests().anyRequest().authenticated()  //任何资源登陆之后才能访问
                .and().logout().logoutUrl("/users/logout")
                .addLogoutHandler(logoutHandler)
                .and()
                .addFilter(new LoginFilter(authenticationManager(), tokenService))
                .addFilter(new MyAuthenticationFilter(authenticationManager(), tokenService, jwtService))
                .httpBasic();
    }

    @Override
    public void configure(WebSecurity web) throws Exception {

    }
}